package jrain.fw.http.tomcat;

import java.io.IOException;

import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import jrain.fw.http.common.consts.ContentType;
import jrain.fw.http.common.consts.HttpCfg;
import jrain.fw.http.common.consts.HttpConsts;

public class PingServlet extends HttpServlet {

	private static final long serialVersionUID = 1L;

	protected void setEncoding(HttpServletRequest request, HttpServletResponse response) throws IOException {
		request.setCharacterEncoding("UTF-8");
		response.setCharacterEncoding("UTF-8");
	}

	protected void setCros(HttpServletRequest request, HttpServletResponse response) {
		response.setHeader(HttpConsts.AccessControlAllowOrigin, HttpCfg.httpCorsOrigin.getValue());
		response.setHeader(HttpConsts.AccessControlAllowMethods, HttpCfg.httpCorsMethods.getValue());
		response.setHeader(HttpConsts.AccessControlAllowHeaders, HttpCfg.httpCorsHeaders.getValue());
	}

	protected void service(HttpServletRequest request, HttpServletResponse response)
			throws ServletException, IOException {
		setEncoding(request, response);
		setCros(request, response);
		if ("OPTIONS".equals(request.getMethod())) {
			return;
		}
		response.setContentType(ContentType.APPLICATION_JSON_UTF8);
		response.getWriter().write("{\"code\":\"200\"}");
	}

}
